<?php



namespace app\admin\controller;

use app\admin\service\NodeService;
use library\Controller;
use library\tools\Data;
use think\Db;
use think\facade\Request;

/**
 * 系统菜单管理
 * Class Menu
 *
 * @package app\admin\controller
 */
class Menu extends Controller
{

    /**
     * 当前操作数据库
     *
     * @var string
     */
    protected $table = 'sys_menu';

    /**
     * 系统菜单管理
     *
     * @auth true
     * @menu true
     */
    public function index()
    {
        $this->title = '系统菜单管理';
        $this->_page($this->table, false);
    }

    /**
     * 列表数据处理
     *
     * @param array $data
     */
    protected function _index_page_filter(&$data)
    {
        foreach ($data as &$vo) {
            if ($vo['url'] !== '#') {
                $vo['url'] = url($vo['url']) . (empty($vo['params']) ? '' : "?{$vo['params']}");
            }
            $vo['ids'] = join(',', Data::getArrSubIds($data, $vo['id']));
        }
        $data = Data::arr2table($data);
    }

    /**
     * 添加系统菜单
     *
     * @auth true
     */
    public function add()
    {
        $this->applyCsrfToken();
        $this->_form($this->table, 'form');
    }

    /**
     * 编辑系统菜单
     *
     * @auth true
     */
    public function save()
    {
        $this->_form($this->table, 'form');
    }

    /**
     * 表单数据处理
     *
     * @param array $vo
     *
     * @throws \ReflectionException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function _form_filter(&$vo)
    {
        if ($this->request->isGet()) {
            $menus = Db::name($this->table)
                       ->where(['status' => '1'])
                       ->order('sort desc,id asc')
                       ->select();
            $menus[] = [
                'title' => '顶级菜单',
                'id'    => '0',
                'pid'   => '-1'
            ];
            foreach ($this->menus = Data::arr2table($menus) as $key => &$menu) {
                if (substr_count($menu['path'], '-') > 3) unset($this->menus[$key]); # 移除三级以下的菜单
                elseif (isset($vo['pid']) && $vo['pid'] !== '' && $cur = "-{$vo['pid']}-{$vo['id']}") {
                    if (stripos("{$menu['path']}-", "{$cur}-") !== false || $menu['path'] === $cur) unset($this->menus[$key]); # 移除与自己相关联的菜单
                }
            }
            // 选择自己的上级菜单
            if (empty($vo['pid']) && $this->request->get('pid', '0')) {
                $vo['pid'] = $this->request->get('pid', '0');
            }
            // 读取系统功能节点
            $this->nodes = NodeService::getMenuNodeList();
        }
    }

    /**
     * 启用系统菜单
     *
     * @auth true
     */
    public function resume()
    {
        $this->applyCsrfToken();
        $this->_save($this->table, ['status' => '1']);
    }

    public function _save_filter(&$vo)
    {
        //获取所有上级
        $data = request()->param();
        //启用 则父类全部要启用
        if (intval($data['status']) == 1) {
            $parents = \db('sys_menu')->select();
            $parent = \db('sys_menu')
                ->where('id', $data['id'])
                ->find();
            $ids = Data::getArrParIds($parents, $parent['pid'], 'id', 'pid');
            \db('sys_menu')
                ->whereIn('id', $ids)
                ->setField('status', $data['status']);
        }
    }

    /**
     * 禁用系统菜单
     *
     * @auth true
     */
    public function forbid()
    {
        $this->applyCsrfToken();
        $this->_save($this->table, ['status' => '0']);
    }

    /**
     * 删除系统菜单
     *
     * @auth true
     */
    public function del()
    {
        $this->_delete($this->table);
    }

    /**
     * 菜单授权
     *
     * @auth   true
     *
     * @author : Randy_chen
     */
    public function apply()
    {
        $action = Request::param('action');
        switch ($action) {
            case 'gets':
                //获取当前角色的菜单
                $tree = Db::name('sys_menu')
                          ->select();

                $data['tree'] = $tree;
                $this->success('数据获取成功', $data);
                break;
            case 'apply':
                //授权
                $data = Request::param();
                $menu_ids = explode(',', $data['menu_ids']);
                $list = [];
                if($data['id']){
                    $role_id = $data['id'];
                    Db::name('system_auth')
                      ->field('title,status,desc,id')
                      ->where('id', $data['id'])
                      ->update($data);
                }else{
                    $role_id = Db::name('system_auth')
                                 ->field('title,status,desc')
                                 ->insertGetId($data);
                }

                foreach ($menu_ids as $v) {
                    $tmp = [];
                    $tmp['role_id'] = $role_id;
                    $tmp['menu_id'] = $v;
                    $list[] = $tmp;
                }
                Db::name('system_role_menu')->where('role_id',$role_id)->delete();
                Db::name('system_role_menu')
                  ->insertAll($list);
                $auth = Db::name('system_auth')->find($role_id);
                $this->success('角色更新成功!', $auth);

            default:
                return false;
        }
    }
}